<template>
  <div class="">
    <el-row>
      <el-col :span="24">
        <div class="page-filter mb10 fl">
          <el-form ref="filter" :model="filter" label-width="0">
            <el-form-item class="mr10 mb5 fl">
              <ProFilter v-model="filter.pro_id" />
            </el-form-item>
            <el-form-item class="mr10 mb5 fl">
              <CustomerSelect v-model="filter.ctm_id" />
            </el-form-item>
            <el-form-item class="mr10 mb5 fl" prop="year">
              <el-date-picker
                v-model="filter.year"
                placeholder="年度"
                type="year"
                format="yyyy"
                value-format="yyyy"
                size="small"
                clearable
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item class="mr10 mb5 fl">
              <el-select v-model="filter.state" size="small" style="width: 100%">
                  <el-option
                    v-for="item in states"
                    :key="item.key"
                    :label="item.value"
                    :value="item.key"
                  />
                </el-select>
            </el-form-item>
            <el-form-item class="mr10 mb5 fl" prop="begin_time">
              <el-date-picker
                v-model="filter.begin_time"
                placeholder="开始时间"
                type="date"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                size="small"
                clearable
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item class="mr10 mb5 fl" prop="end_time">
              <el-date-picker
                v-model="filter.end_time"
                placeholder="结束时间"
                type="date"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                size="small"
                clearable
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item class="mr10 mb5 fl" style="width: 300px">
              <el-button size="small" @click="app.resetFields($refs['filter'].$parent,'filter')">清 空</el-button>
              <el-button type="primary" size="small" @click="getList">查 询</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
      <el-col :span="24">
        <el-row>
          <el-col :span="24" class="h240 pr">
            <div class="m-left pa l0 t0 h200 fs16">
              <div class="m-left-title mt15" style="background-color: blue;">
                <div>{{ filter.year ? filter.year : "本年" }}报价</div>
                <div class="fs20 fw600 mt5">{{ this.yearAmount }}</div>
              </div>
              <div class="m-left-title mt15" style="background-color: cyan">
                <div>当月报价</div>
                <div class="fs20 fw600 mt5">{{ this.monthAmount }}</div>
              </div>
            </div>
            <div class="m-center w100 h240">
              <div id="ba" style="width: 100%; height:240px;" />
            </div>
            <div class="m-right pa r0 t0 h220">
              <div id="bn" style="width: 100%; height:220px" />
            </div>
          </el-col>
        </el-row>
        <el-table
          v-loading="app.loading"
          class="search-table"
          :data="list"
          border
          :summary-method="getSummaries"
          show-summary
          fit
          highlight-current-row
          style="width: 100%;"
        >
          <el-table-column label="序号" align="center" width="56px">
            <template slot-scope="{$index}">
              {{ $index + 1 }}
            </template>
          </el-table-column>
          <el-table-column label="客户名称" width="220px" prop="lc_name" />
          <el-table-column label="项目名称" width="220px" prop="name" :formatter="paytypeFormatter" />
          <el-table-column label="EQ单号" width="190px">
            <template slot-scope="{row}">
              {{ 'PO'+row.id }}
            </template>
          </el-table-column>
          <el-table-column label="立项日期" align="center" width="150px" prop="create_time" />
          <el-table-column label="成本金额 " align="right" width="160px">
            <template slot-scope="{row}">
              {{ app.toFix(row.cost, 2) }}
            </template>
          </el-table-column>
          <el-table-column label="报价金额 " align="right" width="160px">
            <template slot-scope="{row}">
              {{ app.toFix(row.quoted_price, 2) }}
            </template>
          </el-table-column>
          <el-table-column label="客户联系人" width="120px" prop="lcc_name" />
          <el-table-column label="联系电话" width="160px" prop="lcc_phone" />
          <el-table-column label="备注" min-width="260px" prop="remark">
            <template slot-scope="{row}">
              <span v-if="row.remark">{{ row.remark }} <br></span>
              <span v-if="row.bid_remark">{{ row.bid_remark }} <br></span>
              <span v-if="row.progress_remark">{{ row.progress_remark }} <br></span>
              <span v-if="row.order_remark">{{ row.order_remark }} <br></span>
              <span v-if="row.contract_remark">{{ row.contract_remark }} <br></span>
              <span v-if="row.budget_remark">{{ row.budget_remark }} <br></span>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="filter.pageAll>0" :total="filter.pageAll" :page.sync="filter.pageCurrent" :limit.sync="filter.pageNumber" @pagination="getList" />
      </el-col>
    </el-row>
    <XSHK ref="xshk" :get-data="getList" :info="dialog" />
    <Paytypes ref="paytypes" :get-data="getList" :info="dialog" />
    <Funds ref="funds" :get-data="getList" :info="dialog" />
    <Dialog ref="dialog" :info="dialog" />
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { pros, proTotalAmount } from '@/api/statistics/statistics'
import page from '@/utils/page'
import CustomerSelect from '@/myComponents/CustomerSelect'
import XSHK from '@/views/business/components/order/components/xshks-dialog'
import Paytypes from '@/views/business/components/order/components/paytypes-dialog'
import Funds from '@/views/business/components/order/components/funds-dialog'
import Dialog from './components/quoted-dialog'

export default {
  name: '',
  components: { CustomerSelect, Paytypes, Funds, XSHK, Dialog },
  extends: page,
  props: {
    reqList: {
      default: pros,
      type: Function
    }
  },
  data() {
    return {
      parameter: { type: 'quoted' },
      price: {},
      price_summary: {},
      dFieldPaytypes: ['pro_id', 'trading_price'],
      dFieldFunds: ['pro_id', 'paytype'],
      dFieldXSHK: ['pro_id', 'paytype', 'trading_price'],
      states: [{key:'0', value:'跟进'}, {key:1, value:'成交'}, {key:2, value:'丢单'}, {key:3, value:'结束'}],
      yearAmount: 0,
      monthAmount: 0,
      dayAmount: 0,
      quarters: [],
      months: []
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getListBefore() {
      if(!(this.filter.year && this.filter.year != '')) this.$set(this.filter, 'year', new Date().getFullYear()+'')
    },
    paytypeFormatter(e, c) {
      const xshk = e.xshk
      const xshks = []
      if (xshk) {
        const array = xshk.split(',')
        if (array.length > 0) {
          array.forEach(element => {
            const js = element.split('#')
            const f = {}
            f.v = js[0]
            f.m = js[1]
            f.t = js[2]
            xshks.push(f)
          })
        }
      }
      e.xshks = xshks

      const fund = e.fund
      const funds = []
      if (fund) {
        const array = fund.split(',')
        if (array.length > 0) {
          array.forEach(element => {
            const js = element.split('#')
            const f = {}
            f.v = js[0]
            f.m = js[1]
            f.t = js[2]
            funds.push(f)
          })
        }
      }
      e.funds = funds

      const payment = e.payment
      const payments = []
      if (payment) {
        const array = payment.split(',')
        if (array.length > 0) {
          array.forEach(element => {
            const js = element.split('-')
            const f = {}
            f.v = js[0] || ''
            f.s = js[3] || ''
            payments.push(f)
          })
        }
      }
      e.payments = payments

      return e.name
    },
    getListAfter(e) {
      this.handleAmount()
      this.price_summary = e.summary
    },
    handleAmount() {
      proTotalAmount({
        ...this.filter
      }).then(res => {
        this.price = res.info ? res.info : {}
        this.yearAmount = res.yearAmount ? res.yearAmount : 0
        this.monthAmount = res.monthAmount ? res.monthAmount : 0
        this.dayAmount = res.dayAmount ? res.dayAmount : 0
        this.quarters = res.quarters ? res.quarters : []
        this.months = res.months ? res.months : []

        this.handleSAmount()
        this.handleSNum()
      }).catch(err => {
        this.$message.error(err.msg)
      })
    },
    handleSAmount() {
      var chart = document.getElementById('ba')
      var echart = echarts.init(chart)
      let x = []
      let y = []
      this.months.forEach(e=>{
        x.push(e['m'])
        y.push(e['price'])
      })
      x.push("合计")
      y.push(this.yearAmount)
      let option = {
        title: {
          text: '每月报价金额对比图',
          subtext: ''
        },
        tooltip: {},
        // legend: {
        //   data: ['money']
        // },
        xAxis: {
          type: 'category',
          data: x,
          axisLabel: {
            interval: 0,
            rotate: 20
          }
        },
        yAxis: {},
        series: [
          {
            name: '金额',
            type: 'bar',
            data: y,
            itemStyle: {
              barBorderRadius: 0,
              color: '#73c0de',
              borderWidth: 0,
              borderType: 'solid',
              borderColor: '#73c0de',
              shadowColor: '#73c0de',
              shadowBlur: 0
            },
            // label: {
            //   show: true,
            //   rotate: 20,
            //   position: 'top'
            // },
            barWidth: '40%'
          },
        ]
      }
      echart.setOption(option)
      echart.getZr().on('click', params => {
        let pointInPixel = [params.offsetX, params.offsetY]
        if (echart.containPixel('grid', pointInPixel)) {
          let xIndex = echart.convertFromPixel({ seriesIndex: 0 }, [params.offsetX, params.offsetY])[0]
          let month = this.filter.year + '-' + (xIndex+1>=10 ? xIndex+1 : ('0'+(xIndex+1)))
          this.handleDialog({...{month: month}, ...
                    {dRef: 'dialog', dTitle: '报价详情', dType: 'edit', dField: ['month']}})
        }
      })
    },
    handleSNum() {
      var chart = document.getElementById('bn')
      var echart = echarts.init(chart)
      let x = []
      let y = []
      let len = this.quarters.length
      for(let i=0; i<len; i++) {
        x.push(this.quarters[i]['q'])
        y.push(this.app.toFix(this.quarters[i]['price']/10000, 0))
      }
      let option = {
        title: {
          text: '季度报价金额对比图（万）',
          subtext: ''
        },
        tooltip: {},
        xAxis: {
          type: 'category',
          data: x,
          axisLabel: {
            interval: 0,
            rotate: 20
          }
        },
        yAxis: {},
        grid: {
          top: 50,
          left: '2%',
          right: '2%',
          bottom: '3%',
          containLabel: true
        },
        series: [
          {
            name: '金额（万）',
            type: 'bar',
            data: y,
            itemStyle: {
              barBorderRadius: 0,
              color: '#73c0de',
              borderWidth: 0,
              borderType: 'solid',
              borderColor: '#73c0de',
              shadowColor: '#73c0de',
              shadowBlur: 0
            },
            barWidth: '40%'
          },
        ]
      }
      echart.setOption(option)
    },
    getSummaries() {
      const sums = []
      sums[0] = '合计'
      sums[1] = ''
      sums[2] = ''
      sums[3] = ''
      sums[4] = ''
      sums[5] = this.app.toFix(this.price_summary.cost, 2)
      sums[6] = this.app.toFix(this.price_summary.quoted_price, 2)
      return sums
    }
  }
}
</script>
<style scoped>
.m-left {
  width: 180px;
}
.m-left-title{
  padding: 10px;
  height: 70px;
  line-height: 1.2;
  border-radius: 6px;
  color: #FFFFFF;
}
.m-center{
  padding-left: 210px;
  padding-right: 320px;
}
.m-right {
  width: 310px;
}
</style>
